package com.zwj.interview.链表;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Zwj
 * @Date: 2022/9/20 8:44
 */
public class 复制带随机指针的链表 {

    public Node copyRandomList(Node head) {
        if (head == null) {
            return null;
        }
        //map保存着原来的节点和其复制节点的映射关系
        Map<Node, Node> map = new HashMap<>();
        Node cur = head;
        while (cur != null) {
            map.put(cur, new Node(cur.val));
            cur = cur.next;
        }
        cur = head;
        //开始为新生成的节点分配next指针和random指针
        while (cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);
            cur = cur.next;
        }
        return map.get(head);
    }
}